package com.silence.gankio.core.net

import com.google.gson.Gson
import com.silence.gankio.core.app.ConfigType
import com.silence.gankio.core.app.Core
import me.jessyan.retrofiturlmanager.RetrofitUrlManager
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.fastjson.FastJsonConverterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.*
import java.util.concurrent.TimeUnit

class HttpUtil {

    private val TIME_OUT = 60
    private var RETROFIT_CLIENT: Retrofit

    init {
        val BASE_URL: String = Core.getConfigurations()[ConfigType.API_HOST.name] as String

        val HTTP_CLIENT = RetrofitUrlManager
            .getInstance().with(OkHttpClient.Builder())
            .connectTimeout(TIME_OUT.toLong(), TimeUnit.SECONDS)
            .readTimeout(TIME_OUT.toLong(), TimeUnit.SECONDS)
            .writeTimeout(TIME_OUT.toLong(), TimeUnit.SECONDS)
            .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
            .build()

        RETROFIT_CLIENT = Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .client(HTTP_CLIENT)
            .build()
    }

    companion object {

        private object PARAMS_HOLDER {
            val PARAMS = WeakHashMap<String, Any>()
        }

        fun getParams(): WeakHashMap<String, Any> {
            return PARAMS_HOLDER.PARAMS
        }

        private object Holder {
            val INSTANCE = HttpUtil()
        }

        fun getInstance() = Holder.INSTANCE
    }

    fun <T> getService(clazz: Class<T>): T {
        return RETROFIT_CLIENT.create(clazz)
    }
}